package com.yunji.order.business;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.yunji.common.base.BaseBusiness;
import com.yunji.common.utils.TimeUtils;
import com.yunji.common.utils.bean.BeanUtils;
import com.yunji.order.domain.PayoutDO;
import com.yunji.order.emuns.RemoteTypes;
import com.yunji.order.service.RequestService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Project: yunji-coffee
 * @Package: com.yunji.order.business
 * @Title: AlipayBusiness
 * @Description: 阿里支付业务处理
 * <p>
 * History:
 * Date						Version			Author			Summary
 * ========================================================================
 * 2024-04-22 13:58:34		V1.0			HuaAo		新建类
 */
@Component
public class AlipayBusiness extends BaseBusiness {
    // 验签字符集
    private static final String SIGN_CHARSET = "utf-8";

    @Value("${yunji.profile:xxx}")
    private String profile;

    @Resource
    private PayoutBusiness payoutBusiness;

    @Resource
    private RequestService requestService;

    /**
     * @return Map<String, String> 返回信息
     * @Title checkSign
     * @Desc 验证签名信息
     * @Date 2024-04-23 12:00:30.173
     */
    public Map<String, String> checkSign() throws AlipayApiException {
        Map<String, String> result = getParams();
        String appPublicCert = profile + "/alipay/alipayCertPublicKey_RSA2.crt";
        requestService.updateRequest(result.get("out_biz_no"), RemoteTypes.ALIPAY_TRADE_PAYOUT.getCode(), result.get("status"), BeanUtils.toString(result));
        logs.info("【支付宝验签】:证书路径:{},解析数据:{}", appPublicCert, result);
        boolean signVerified = AlipaySignature.rsaCertCheckV1(result, appPublicCert, SIGN_CHARSET, "RSA2");
        Assert.isTrue(signVerified, "验签失败!");
        return result;
    }

    /**
     * @return Map<String, String>
     * @Title getParams
     * @Desc 获取参数信息
     * @Date 2024-04-24 16:30:55.479
     */
    private Map<String, String> getParams() {
        Map<String, String> result = new HashMap<>();
        Map<String, String[]> params = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : params.entrySet()) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            result.put(name, valueStr);
        }
        return result;
    }

    /**
     * @return Map<String, Object>
     * @Title payout
     * @Desc 用户转账业务处理
     * @Date 2024-04-22 14:23:08.511
     */
    public String payout() {
        String response = "error";
        try {
            Map<String, String> result = checkSign();
            String content = result.get("biz_content");
            logs.info("【支付宝回调】回调信息:{}", content);
            JSONObject json = JSONObject.parseObject(content);
            String payoutCode = json.getString("out_biz_no");
            logs.info("【支付宝回调】转账流水号{}", payoutCode);
            String payCode = json.getString("pay_fund_order_id");
            String payTime = json.getString("pay_date");
            payoutBusiness.callback(payoutCode,payCode,payTime);
            response = "success";
        }   catch (Exception e) {
            logs.error("【支付宝回调】程序异常:", e);
        }
        return response;
    }
}